package affd.logic;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

/**
 * A Config is a utility to load config files.
 * 
 * @author Joteitti joteitti@cc.hut.fi
 *
 */
public class Config {
	
	private HashMap<String, String> configs;
	
	/**
	 * Constructs a collection of configuration properties.
	 * 
	 * @param filename Filename to be loaded.
	 * @param encoding Encoding to be used.
	 * @throws LogicException
	 */
	public Config(String filename) throws LogicException {
		// Load configuration file
		configs = new HashMap<String, String>();
		
		// Open file for reading
		try {
			BufferedReader reader = Utilities.createReader(filename, null);
			String line = reader.readLine();
			while(line != null) {
				// Parse line
				String[] splitted = line.split("=", 2);
				if(splitted.length > 0) {
					// Get parameter name
					String name = splitted[0].trim();
					
					// Skip comments
					if(!name.startsWith("#")) {		
						// Get parameter value
						if(splitted.length == 2) {
							configs.put(name, splitted[1].trim());
						}
						else {
							configs.put(name, "");
						}
					}
				}
				
				line = reader.readLine();
			}
			
			reader.close();
		}
		catch (Exception e) {
			throw new LogicException("Failed to load configuration !", e);
		}
	}
	
	/**
	 * Gets the property value.
	 * 
	 * @param property Property to get.
	 * @return Value of the property if found otherwise null.
	 */
	public String getValue(String property) {
		// Get value from hash map
		return configs.get(property);
	}

}
